package main

import (
	"time"
	"fmt"
	"log"
	"net/http"
)

/**
 * 通过http请求接口/访问资源文件
 */
func main()  {
	const base_format = "2006-01-02 15:04:05"
	// 普通请求
	http.HandleFunc("/user", func(writer http.ResponseWriter, request *http.Request) {
		num,err := writer.Write([]byte(("hello,world -->"+time.Now().Format(base_format))))
		if err != nil{
			fmt.Println(err.Error())
			return
		}
		fmt.Println("发送字节数:",num)
	})

	// 异常捕获
	http.HandleFunc("/info", func(writer http.ResponseWriter, request *http.Request) {
		defer func() {
			if err := recover();err != nil{
				_,err := writer.Write([]byte(err.(string)))
				if err != nil {
					fmt.Println(err.Error())
				}
			}
		}()
		panic("抛出一个异常")
	})

	// 静态文件
	file := http.FileServer(http.Dir("./static"))
	http.Handle("/static/",http.StripPrefix("/static/",file))

	err := http.ListenAndServe(":8080",nil)
	if err != nil {
		log.Fatal(err.Error())
	}
}
